﻿@{
    Layout = null;
    string stockInTypeListJson = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.StockInTypeList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
    string stockInOrderStatusList = System.Text.Json.JsonSerializer.Serialize(
        ViewBag.StockInOrderStatusList ?? new List<Model.WmsDictData>(),
        new System.Text.Json.JsonSerializerOptions
        {
            ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles,
            Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        }
    );
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>新增订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        .basicInfo {
            width: 82%;
            height: 600px;
            background-color: #fff;
            padding-top: 20px;
            margin-top: 30px;
            margin-left: 20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .stockUpDetail {
            width: 82%;
            min-height: 530px;
            background-color: #fff;
            padding-top: 10px;
            margin-left: 20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .uploadAttachment {
            width: 82%;
            min-height: 450px;
            background-color: #fff;
            padding-top: 10px;
            margin-left: 20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .saveBlock {
            display: grid;
            place-items: center;
            position: sticky;
            bottom: 0;
            width: 100%;
            height: 60px;
            background-color: #fff;
            z-index: 20;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .titleH {
            margin-left: 40px;
        }

        .orderTable {
            margin: 0 auto;
            width: 80%;
            border-spacing: 0 40px;
        }

        .imp {
            color: red;
        }

        .orderTable tbody tr td {
            border-spacing: 0 20px;
        }

        .custom-readonly-input .el-input__inner {
            background-color: #f0f0f0 !important;
            padding: 0px;
        }

        .custom-readonly-input .el-input__wrapper {
            background-color: #f0f0f0 !important;
        }

        /* 树控件样式优化 */
        .el-tree {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
        }

        .tree-title {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .detailBlock {
            padding-left: 30px;
        }

        .uploadAttach {
            padding-top: 30px;
            padding-left: 60px;
        }

        .searchBlock {
            display: inline;
        }

        .buttonBlock {
            display: inline;
            margin-left: 60%;
        }

        /* 合计行样式优化 */
        .el-table__footer-wrapper {
            font-weight: bold;
            background-color: #f5f7fa;
        }

            .el-table__footer-wrapper td {
                text-align: center !important;
            }

        .promptWord {
            color: #606266;
        }

        .upload-demo {
            display: inline-block;
        }

        .btnBlock {
            margin-left: auto;
            padding: 10px 20px 10px 10px;
        }

        .pagination-container {
            margin-left: 45%;
        }

        .valueV {
            color: orangered;
            font-weight: bolder;
        }
        .mainBlock{
            font-size: 16px;
            display:flex;
            justify-content:center;
        }

        .usersBlock .selected {
            background-color: #E3F5ED;
            cursor: pointer;
        }
        .tree-title{
            font-size:16px;
            font-weight:bold;
        }

        .el-tree-node.is-current > .el-tree-node__content {
            background-color: #E3F5ED !important; /* 替换为你的目标颜色 */
        }

        .el-tree-node__content {
            padding: 12px 16px;
        }
        .orderTitleContent{
            color:red;
            font-weight:bold;
        }
    </style>
    <style scoped>

    </style>
</head>
<body>
    <div id="app" class="common-layout"
         data-stock-in-type-list="@stockInTypeListJson"
         data-stock-in-order-status-list="@stockInOrderStatusList">
        <div class="basicInfo">
            <h2 class="titleH">基础信息</h2>
            <hr />
            <div class="basicInfoForm">
                <table class="orderTable">
                    <tbody>
                        <!-- 第一行：入库单号、入库类型 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;入库单号
                            </td>
                            <td>
                                <el-input type="text"
                                          v-model="purchaseOrderCode"
                                          style="width:70%;"
                                          readonly
                                          placeholder="自动获取系统编号">
                                </el-input>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;入库类型
                            </td>
                            <td>
                                <el-select placeholder="请选择"
                                           style="width:90%;"
                                           v-model="selectedStockType">
                                    <el-option v-for="(type, index) in stockInTypeList"
                                               :key="index"
                                               :label="type.Name"
                                               :value="type.Code">
                                    </el-option>
                                </el-select>
                            </td>
                        </tr>

                        <!-- 第二行：仓库名称、入库日期 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;仓库名称
                            </td>
                            <td>
                                <el-select placeholder="请选择仓库"
                                           style="width:70%;"
                                           v-model="selectedWarehouseId"
                                           v-on:change ="handleWarehouseChange"
                                           v-if="warehouseList.length > 0">
                                    <el-option v-for="warehouse in warehouseList"
                                               :key="warehouse.wareHouseId"
                                               :label="warehouse.warehouseName"
                                               :value="Number(warehouse.wareHouseId)">
                                    </el-option>
                                </el-select>
                                <el-button style="border:0px;color:limegreen">设置</el-button>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;入库日期
                            </td>
                            <td>
                                <el-date-picker type="date"
                                                placeholder="请选择日期"
                                                style="width:90%;"
                                                v-model="purchaseDate"
                                                value-format="YYYY-MM-DD"
                                                v-on:change="handleDateChange">
                                    <!-- 新增事件监听 -->
                                </el-date-picker>
                            </td>
                        </tr>

                        <!-- 第三行：关联单号、供应商（修改后） -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;关联单号
                            </td>
                            <td>
                                <el-input placeholder="请选择或输入"
                                          v-model="relatedOrderCode"
                                          style="width:70%;"
                                          :readonly="isRelatePurchase"
                                          v-on:click="isRelatePurchase ? (selectPurchaseOrderDialog = true) : ''">
                                </el-input>
                                <el-checkbox v-model="isRelatePurchase" style="margin-left:8px;">关联进货单号</el-checkbox>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;供应商
                            </td>
                            <td>
                                <!-- 供应商下拉框（替换原输入框+模态框） -->
                                <el-select placeholder="请选择供应商"
                                           style="width:90%;"
                                           v-model="selectedSupplierId"
                                           :disabled="isRelatePurchase"
                                           v-on:change="handleSupplierChange">
                                    <el-option v-for="supplier in supplierList"
                                               :key="supplier.supplierId"
                                               :label="supplier.supplierName"
                                               :value="supplier.supplierId">
                                    </el-option>
                                </el-select>
                            </td>
                        </tr>

                        <!-- 第四行：联系人、联系方式（保持只读，新增样式类） -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系人
                            </td>
                            <td>
                                <el-input placeholder="请选择供应商后自动填充"
                                          v-model="contactPerson"
                                          style="width:70%;"
                                          readonly
                                          class="custom-readonly-input">
                                </el-input>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系方式
                            </td>
                            <td>
                                <el-input placeholder="请选择供应商后自动填充"
                                          v-model="contactPhone"
                                          style="width:90%;"
                                          readonly
                                          class="custom-readonly-input">
                                </el-input>
                            </td>
                        </tr>

                        <!-- 第五行：经办人 -->
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;经办人
                            </td>
                            <td>
                                <el-input placeholder="请选择"
                                          v-model="operatorName"
                                          style="width:70%;"
                                          v-on:click="selectOperatorModel=true"
                                          lable="operatorId"
                                          readonly>
                                </el-input>
                                <!-- 可扩展选择弹窗逻辑，如 v-on:click="openOperatorModal" -->
                            </td>
                        </tr>

                        <!-- 第六行：备注 -->
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注
                            </td>
                            <td colspan="3">
                                <el-input placeholder="请输入"
                                          v-model="remark"
                                          style="width:100%;"
                                          type="textarea"
                                          readonly>
                                </el-input>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="stockUpDetail">
            <h2 class="titleH">进货明细</h2>
            <hr />
            <div class="detailBlock">
                <div class="addAndRemove">
                    <el-button type="success" v-on:click="openAddGoodsDialog">添加</el-button>&nbsp;&nbsp;&nbsp;
                    <el-button type="danger" v-on:click="removeGoodsDetail">移除</el-button>
                </div>
                <div class="detailTable">
                    <el-table :data="goodsDetailData"
                              style="width: 1600px; margin-top: 10px"
                              v-on:selection-change="handleSelectionChange('detail', $event)"
                              ref="detailTable"
                              stripe>
                        <!-- 原有列（序号、名称、编号等）保持不变 -->
                        <el-table-column fixed type="selection" width="50"></el-table-column>
                        <el-table-column fixed prop="id" label="序号" width="70"></el-table-column>
                        <!-- 货品名称：对应goodsName -->
                        <el-table-column fixed prop="goodsName" label="货品名称" width="100"></el-table-column>
                        <!-- 货品编号：对应goodsCode -->
                        <el-table-column fixed prop="goodsCode" label="货品编号" width="130"></el-table-column>
                        <!-- 货品类型：对应category -->
                        <el-table-column prop="goodsTypeName" label="货品类型" width="100"></el-table-column>
                        <!-- 规格型号：对应specification -->
                        <el-table-column prop="specification" label="规格型号" width="80"></el-table-column>
                        <!-- 单位：对应unit -->
                        <el-table-column prop="unit" label="单位" width="80">吨</el-table-column>
                        <!-- 当前库存：prop 正确，保持不变 -->
                        <el-table-column prop="availableInventoryQty" label="当前库存" width="100" :formatter="formatNumber"></el-table-column>

                        <!-- 1. 进货数量：prop 改为实体类的 OrderQuantity（纯展示） -->
                        <el-table-column prop="orderQuantity" label="进货数量" width="100" :formatter="formatNumber"></el-table-column>

                        <!-- 2. 已入库数量：prop 改为实体类的 ReceivedQuantity（纯展示） -->
                        <el-table-column prop="receivedQuantity" label="已入库数量" width="100" :formatter="formatNumber"></el-table-column>

                        <!-- 3. 未入库数量：prop 改为实体类的 NonPurchaseQuantity（纯展示，实体类已计算） -->
                        <el-table-column prop="nonPurchaseQuantity" label="未入库数量" width="100" :formatter="formatNumber"></el-table-column>

                        <!-- 入库库位：保持不变（下拉选择） -->
                        <el-table-column prop="storageLocationId" label="入库库位" width="130">
                            <template #default="scope">
                                <el-select v-model="scope.row.storageLocationId"
                                           placeholder="请选择"
                                           style="width: 100%"
                                           :disabled="!selectedWarehouseId"
                                    v-on:click="handleLocationSelectClick">
                                    <el-option
                                        v-for="(item, index) in locationList"
                                        :key="index"
                                        :label="item.storageLocationName"
                                        :value="item.storageLocationId">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>

                        <!-- 本次入库数量：保持不变（仅这列需要手动输入） -->
                        <el-table-column prop="currentInStockQty" label="本次入库数量" width="130">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.currentInStockQty"
                                          style="width: 100%"
                                          v-on:input="handleCurrentInStockQtyInput(scope.row)"
                                          clearable></el-input>
                            </template>
                        </el-table-column>

                        <!-- 4. 进货单价：prop 改为实体类的 PurchaseUnitPrice（纯展示，无需手动输入） -->
                        <el-table-column prop="purchaseUnitPrice" label="进货单价(元)" width="110" :formatter="formatNumber"></el-table-column>

                        <!-- 5. 进货金额：prop 改为实体类的 PurchaseUnitCount（纯展示，实体类已计算总金额） -->
                        <el-table-column label="进货金额" width="90" :formatter="calculateInboundAmount"></el-table-column>

                        <!-- 批次号、备注、操作列：保持不变 -->
                        <!--批次号-->
                        <el-table-column prop="batchNo" label="批次号" width="100">
                            <template #default="scope">
                                <el-input v-model="scope.row.batchNo"
                                          style="width: 100%"
                                          clearable></el-input>
                            </template>
                        </el-table-column>
                        <!-- 备注 -->
                        <el-table-column prop="remarks" label="备注" width="200">
                            <template #default="scope">
                                <el-input type="textarea"
                                          v-model="scope.row.remarks"
                                          placeholder="请输入备注"
                                          :rows="3"
                                          style="width: 100%"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="180">
                            <template #default="scope">
                                <el-button class="operate-btn"
                                           link type="primary" size="default"
                                           v-on:click="removeDetail(scope.row)">
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 合计行：保持不变 -->
                    <div class="fixed-full-row" style="border-bottom:1px solid #f0f0f0;height:28px;padding:10px 0px">
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="promptWord">合计</span>
                        <div class="countNum" style="display:inline-block;margin-left:45%">
                            <span class="promptWord">未入库数量: <span class="valueV">{{ nonPurchaseQuantity }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">已入库数量: <span class="valueV">{{ receivedQuantity }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">入库种类: <span class="valueV">{{ totalCategories }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">入库数量: <span class="valueV">{{ formatNumber(null, null, inboundTotalQuantity) }}</span>吨</span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">总金额: <span class="valueV">{{ formatNumber(null, null, totalAmount) }}</span>元</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="uploadAttachment">
            <h2 class="titleH">上传附件</h2>
            <hr />
            <div class="uploadAttach">
                <!-- 文件选择组件（仅负责选择，不上传） -->
                <el-upload class="upload-demo"
                           action="/WhInbound/UploadAttachment"
                             name="file"
                             :file-list="tempFileList"
                             :show-file-list="false"
                             accept=".doc,.docx,.pdf,.rar,.zip"
                             :limit="10"
                             :on-exceed="handleFileExceed"
                             :on-success="handleUploadSuccess"
                             :on-remove="handleFileRemove"
                           >
                  <el-button type="primary">选择文件</el-button>
                </el-upload>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">支持格式：doc,docx,pdf,rar,zip | 单个文件≤200MB | 最多10个文件</span>

                <!-- 自定义文件列表（仅显示文件名） -->
                <div class="attachmentFile" style="margin-top: 20px;">
                    <div v-for="(file, index) in tempFileList"
                         :key="file.uid"
                         class="file-item"
                         style="width:60%;display: flex; align-items: center; margin: 10px 0; padding: 8px; border: 1px solid #eee; border-radius: 4px;">
                        <span style="flex: 1;">{{ file.name }}</span>
                        <el-button size="small"
                                   type="text"
                                   style="color: #ff4d4f;"
                                   v-on:click="removeTempFile(index)">
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        <div class="saveBlock">
            <div class="btnBlock">
                <el-button v-on:click="closeDetail">关闭</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAsDraft">保存草稿</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAndAdd">保存并新增</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success" v-on:click="saveThis">保存</el-button>
            </div>
        </div>

        @* 选择关联单号模态框 *@
        <el-dialog v-model="selectPurchaseOrderDialog"
                   :width="1000"
                   :modal="false">
            <!-- 筛选区域（保持不变） -->
            <h3>选择进货单</h3>
            <hr />
            <br/>
            <div style="margin-bottom: 16px; display: flex; align-items: center; flex-wrap: wrap;">
                <div class="upBlock">
                    <el-input v-model="searchParams.orderNo"
                              placeholder="请输入进货单号"
                              style="width: 200px; margin-right: 10px;"
                              clearable></el-input>
                    <el-select v-model="searchParams.orderStatus"
                               placeholder="请选择单据状态"
                               style="width: 200px; margin-right: 10px;"
                               clearable>
                        <el-option v-for="(status, idx) in orderStatusOptions"
                                   :key="idx"
                                   :label="status.label"
                                   :value="status.value"></el-option>
                    </el-select>
                    <el-select v-model="searchParams.supplierId"
                               placeholder="请选择供应商"
                               style="width: 200px; margin-right: 10px;"
                               clearable>
                        <!-- 循环后端返回的 supplierList，显示真实供应商名称，传递ID -->
                        <el-option v-for="supplier in supplierList"
                                   :key="supplier.supplierId"
                                   :label="supplier.supplierName"
                                   :value="supplier.supplierId">
                        </el-option>
                    </el-select>
                </div>
                <div class="downBlock" style="margin-top:30px">
                    <el-select v-model="filterState.selectedPersonId"
                               v-on:change="handlePersonChange"
                               placeholder="请选择进货人"
                               style="width: 200px; margin-right: 10px;"
                               value-key="id">
                        <el-option v-for="person in filterState.filteredPersons"
                                   :key="person.id"
                                   :label="person.name"
                                   :value="person.id"></el-option>
                    </el-select>

                    <el-tree-select v-model="filterState.selectedDeptId"
                                    :data="filterDepartTree"
                                    :props="{ label: 'name', value: 'id', children: 'children' }"
                                    style="width: 200px; margin-right: 10px;"
                                    placeholder="请选择进货部门"
                                    v-on:change="handleDepartmentChange">
                    </el-tree-select>

                    <el-date-picker v-model="searchParams.buyerDate"
                                    type="date"
                                    placeholder="请选择进货日期"
                                    style="width: 200px; margin-right: 10px;"
                                    value-format="YYYY-MM-DD"></el-date-picker>
                    <div class="buttonBlock" style="margin-left:200px">
                        <el-button type="primary" v-on:click ="handleSearch">查询</el-button>
                        <el-button v-on:click ="handleReset">重置</el-button>
                    </div>
                </div>
            </div>

            <!-- 进货单表格（核心修改：多选改单选+序号列） -->
            <el-table :data="tableData"
                      style="width: 100%;"
                      ref="purchaseTable">
                <!-- 添加ref用于清空选中 -->
                <!-- 第一列：单选框（替换原selection多选框） -->
                <el-table-column label="序号" width="80" align="center">
                    <template #default="scope">
                        <el-radio v-model="selectedPurchaseId"
                                  :label="scope.row.upOrderId"
                          v-on:change="handleRadioSelect(scope.row)">
                    {{ (pagination.currentPage - 1) * pagination.pageSize + scope.$index + 1 }}
                </el-radio>
                    </template>
                </el-table-column>
                <!-- 原有列保持不变 -->
                <el-table-column prop="upOrderNo" label="进货单号" width="150"></el-table-column>
                <el-table-column prop="orderStatus" label="单据状态" width="100">
                    <template #default="scope">
                        <!-- 主动转换为字符串 -->
                        {{ getStatusName(String(scope.row.orderStatus)) }}
                    </template>
                </el-table-column>
                <el-table-column prop="buyerDate" label="进货日期" width="120">
                    <!-- 日期格式化（可选，若后端返回时间戳需处理） -->
                    <template #default="scope">
                        {{ new Date(scope.row.buyerDate).toLocaleDateString() }}
                    </template>
                </el-table-column>
                <el-table-column prop="supplierName" label="供应商" width="120"></el-table-column>
                <el-table-column prop="buyerOrgName" label="进货部门" width="120"></el-table-column>
                <el-table-column prop="usersName" label="进货人" width="90"></el-table-column>
                <el-table-column prop="orderQuantity" label="货品数量" width="80" align="right">
                    <template #default="scope">{{ scope.row.orderQuantity || 0 }}</template>
                </el-table-column>
                <el-table-column prop="purchaseUnitPrice" label="进货金额" width="80" align="right">
                    <template #default="scope">{{ (scope.row.purchaseUnitPrice || 0).toFixed(2) }}</template>
                </el-table-column>
            </el-table>

            <!-- 分页组件（保持不变） -->
            <div style="margin-top: 16px; text-align: right;">
                <el-pagination v-model:current-page="pagination.currentPage"
                               v-model:page-size="pagination.pageSize"
                               :total="pagination.total"
                               :page-sizes="[10, 20, 50, 100]"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handlePageSizeChange"
                               v-on:current-change="handlePageChange" />
            </div>

            <!-- 底部按钮（保持不变） -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="selectPurchaseOrderDialog = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmSelect">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 选择经办人模态框 *@
        <el-dialog v-model="selectOperatorModel" :width="1000" :modal="false">
            <h3>选择人员</h3>
            <hr />
            <br />
            <div class="mainBlock" style="border:1px solid #aaa">
                <!-- 左侧：机构选择树 -->
                <div class="organazationBlock" style="width:350px;border-right:1px solid #aaa;display:inline-block;padding:10px;">
                    <div class="tree-title" style="margin:10px">机构选择</div>
                    <el-tree :data="filterDepartTree"
                             :props="{ label: 'name', value: 'id', children: 'children' }"
                             v-on:node-click="handleOrgSelect"
                             highlight-current
                             current-node-class="org-tree-selected" />
                </div>
                <!-- 中间：人员列表（根据机构筛选） -->
                <div class="usersBlock" style="width:300px;border-right:1px solid #aaa;display:inline-block;padding:10px;">
                    <div class="tree-title" style="margin:10px">人员选择</div>
                    <el-scrollbar style="height: 400px;">
                        <ul style="list-style: none;padding-left: 0;margin: 0;">
                            <li v-for="user in filteredUsers"
                                :key="user.id"
                                v-on:click="handleUserSelect(user)"
                                :class="{ 'selected': selectedUsers.some(item => item.id === user.id) }"
                                style="list-style-type: none;padding:10px">
                                {{ user.name }}
                            </li>
                        </ul>
                    </el-scrollbar>
                </div>
                <!-- 右侧：已选择人员展示 -->
                <div class="selectedUser" style="width:300px;display:inline-block;padding:10px;">
                    <div class="tree-title" style="margin:10px">已选择</div>
                    <div v-if="selectedUsers.length === 0" style="margin:10px">暂无选择</div>
                    <div v-else>
                        <div v-for="(user, index) in selectedUsers"
                             :key="user.id"
                             style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                            <span style="padding:10px;background-color:#E3F5ED;width:100%">{{ user.name }}</span>
                            <!-- 保留删除按钮，允许取消选择 -->
                            <el-icon v-on:click="removeSelectedUser(index)" style="margin-left:8px;cursor:pointer"><Close /></el-icon>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="selectOperatorModel = false">取消</el-button>
                    <el-button type="primary" v-on:click ="confirmOperatorSelect">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 添加入库货品模态框 *@
        <el-dialog v-model="addGoodsDialog" :modal="false" style="width:63%">
            <h3>添加货品</h3>
            <hr/>
            <br/>
            <div class="orderInfo" style="margin-bottom:15px;">
                <!-- 进货单号：关联单号（relatedOrderCode） -->
                <span class="orderTitle">进货单号:</span>
                <span class="orderTitleContent">{{ selectedPurchaseRow.upOrderNo || '未选择' }}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                <!-- 进货日期：选中进货单的 BuyerDate（格式化日期） -->
                <span class="orderTitle">进货日期:</span>
                <span class="orderTitleContent">
                    {{ selectedPurchaseRow?.buyerDate ? new Date(selectedPurchaseRow.buyerDate).toLocaleDateString() : '未选择' }}
                </span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                <!-- 供应商：选中进货单的 SupplierName -->
                <span class="orderTitle">供应商:</span>
                <span class="orderTitleContent">{{ selectedPurchaseRow?.supplierName || '未选择' }}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                <!-- 金额：选中进货单的总金额（PurchaseUnitPrice，保留2位小数） -->
                <span class="orderTitle">金额:</span>
                <span class="orderTitleContent">
                    {{ selectedPurchaseRow?.purchaseUnitPrice ? Number(selectedPurchaseRow.purchaseUnitPrice).toFixed(2) : '0.00' }}
                </span>元&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                <!-- 数量：选中进货单的总数量（OrderQuantity，保留2位小数） -->
                <span class="orderTitle">数量:</span>
                <span class="orderTitleContent">
                    {{ selectedPurchaseRow?.orderQuantity ? Number(selectedPurchaseRow.orderQuantity).toFixed(2) : '0.00' }}
                </span>吨
            </div>
            <div class="addDetailsMain">
                <!-- 搜索区域 -->
                @* <div class="searchBlock">
                    <el-input type="text"
                              placeholder="请输入货品编号/名称"
                              style="width:300px"
                              v-model="goodsSearchKey"
                              clearable
                              v-on:keyup.enter="searchGoods">
                    </el-input>
                </div>
                <div class="buttonBlock">
                    <el-button v-on:click="resetGoodsSearch">重置</el-button>
                    <el-button type="success" v-on:click="searchGoods">查询</el-button>
                </div> *@

                <!-- 货品表格 -->
                <div class="goodsDetailTable">
                    <el-table :data="paginatedGoodsData" 
                    style="width: 100%; margin-top: 10px" 
                    ref="addTable" 
                    stripe 
                    v-on:selection-change="handleGoodsSelectionChange">
                        <el-table-column type="selection" width="50"></el-table-column>
                        <el-table-column label="序号" width="70">
                            <template #default="scope">
                                {{ (goodsCurrentPage - 1) * goodsPageSize + scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <!-- 字段与 OmPurOrderGoodsDetail 实体对齐 -->
                        <el-table-column prop="goodsCode" label="货品编号" width="160"></el-table-column>
                        <el-table-column prop="goodsName" label="货品名称" width="100"></el-table-column>
                        <el-table-column prop="specification" label="规格型号" width="100"></el-table-column>
                        <el-table-column label="单位" width="80">吨</el-table-column> 
                        <el-table-column prop="purchaseUnitPrice" label="进货单价(元)" width="120" :formatter="formatNumber"></el-table-column>
                        <el-table-column prop="orderQuantity" label="进货数量" width="100" :formatter="formatNumber"></el-table-column>
                        <el-table-column prop="purchaseUnitCount" label="进货金额" width="100" :formatter="formatNumber"></el-table-column>
                        <el-table-column prop="receivedQuantity" label="已入库" width="100" :formatter="formatNumber"></el-table-column>
                        <el-table-column prop="nonPurchaseQuantity" label="未入库" width="100" :formatter="formatNumber"></el-table-column>
                    </el-table>
                    <!-- 分页组件（核心修改：与主页面分页逻辑对齐） -->
                    <div class="pagination-container" style="margin-top: 16px;">
                        <el-pagination v-model:current-page="goodsCurrentPage"
                                       v-model:page-size="goodsPageSize"
                                       :page-sizes="[10, 20, 50, 100]"
                                       :total="goodsTotal"
                                       layout="total, sizes, prev, pager, next, jumper"
                                       v-on:size-change="handleGoodsPageSizeChange"
                                       v-on:current-change="handleGoodsPageChange">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="addGoodsDialog = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmAddGoods">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, reactive, watch, nextTick } = Vue;
        const { ElMessageBox, ElMessage } = ElementPlus;
        const app = createApp({
            setup() {
                // 基础变量定义
                const stockInTypeList = ref([]);
                const selectedStockType = ref('');
                const warehouseList = ref([]);
                const selectedWarehouseId = ref();
                const purchaseOrderCode = ref('');
                const relatedOrderCode = ref('');
                const isRelatePurchase = ref(false);
                const supplierName = ref('');
                const contactPerson = ref('');
                const contactPhone = ref('');
                const operatorName = ref('');
                const operatorId = ref(0);
                const remark = ref('');
                const selectOperatorModel = ref(false);
                const saveBtnDisabled = ref(false);

                // 状态字典相关
                const stockinOrderStatusDict = ref([]);
                const orderStatusOptions = ref([]);

                // 货品明细相关
                const goodsDetailData = ref([]);
                const selectedRows = ref({ detail: [], add: [] });
                const totalCategories = ref(0);
                const totalQuantity = ref(0);
                const totalAmount = ref(0);

                // 模态框相关
                const relatedUpOrderId = ref(0);
                const originalGoodsData = ref([]);
                const addGoodsDialog = ref(false);
                const goodsSearchKey = ref('');
                const goodsCurrentPage = ref(1);
                const goodsPageSize = ref(10);
                const goodsTotal = ref(0);
                const paginatedGoodsData = ref([]);

                // 供应商相关
                const supplierList = ref([]);
                const selectedSupplierId = ref('');

                // 进货单选择相关
                const selectedPurchaseId = ref('');
                const selectedPurchaseRow = ref(null);
                const selectPurchaseOrderDialog = ref(false);
                const searchParams = reactive({
                    orderNo: '',
                    orderStatus: '',
                    supplierName: '',
                    buyerName: '',
                    orgName: '',
                    buyerDate: ''
                });
                const tableData = ref([]);
                const pagination = reactive({
                    currentPage: 1,
                    pageSize: 10,
                    total: 0
                });
                const selectedPurchaseOrders = ref([]);

                // 部门/人员筛选相关
                const filterDepartTree = ref([]);
                const filterDepartList = ref([]);
                const treeProps = ref({
                    children: 'children',
                    label: 'label'
                });
                const filterAllManData = ref([]);
                const filterManData = ref([]);

                //-----------------------------------部门-------------------------------------

                // 部门与人员相关变量定义
                const filterState = reactive({
                    selectedDeptId: '',
                    selectedDeptName: '',
                    selectedPersonId: '',
                    selectedPersonName: '',
                    filteredPersons: []
                });

                const purchaseDate = ref(''); // 原有变量，确保已定义

                const handleDateChange = async (selectedDate) => {
                    if (!selectedDate) return; // 未选择日期时直接返回
                    const selected = new Date(selectedDate);
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);

                    // 2. 若选择日期 > 今天，触发弹窗提醒
                    if (selected > today) {
                        try {
                            await ElMessageBox.confirm(
                                '当前选择日期已超过当前时间，是否继续？',
                                '日期提醒',
                                {
                                    confirmButtonText: '继续',
                                    cancelButtonText: '取消',
                                    type: 'warning' // 警告类型弹窗，样式更醒目
                                }
                            );
                        } catch (error) {
                            purchaseDate.value = '';
                        }
                    }
                };

                

                // 部门选择变化处理（调整为 ref 语法）
                const handleDepartmentChange = (deptId) => {
                    if (!deptId) {
                        // 错误：filterState.value.filteredPersons → 正确：filterState.filteredPersons
                        filterState.filteredPersons = [...filterAllManData.value];
                        return;
                    }

                    // 查找选中的部门（filterDepartTree 是 ref，仍需 .value）
                    const selectedDept = findTreeNode(filterDepartTree.value, String(deptId));
                    if (!selectedDept) {
                        ElMessage.warning('未找到选中的部门');
                        filterState.filteredPersons = [];
                        return;
                    }

                    // 错误：filterState.value.selectedDeptId → 正确：filterState.selectedDeptId
                    filterState.selectedDeptId = String(deptId);
                    filterState.selectedDeptName = selectedDept.name;
                    searchParams.orgName = selectedDept.name;

                    // 后续筛选人员逻辑
                    const allChildDeptIds = getDeptIdsRecursive(selectedDept);
                    filterState.filteredPersons = filterAllManData.value.filter(person =>
                        allChildDeptIds.includes(String(person.orgId))
                    );
                };

                // 辅助函数：递归获取部门及子部门ID（不变）
                const getDeptIdsRecursive = (dept) => {
                    const ids = [dept.id];
                    if (dept.children && dept.children.length > 0) {
                        dept.children.forEach(child => {
                            ids.push(...getDeptIdsRecursive(child));
                        });
                    }
                    return ids;
                };

                // 人员选择变化处理
                const handlePersonChange = (personId) => {
                    // 1. 重置状态
                    filterState.selectedDeptId = '';
                    filterState.selectedPersonId = '';
                    searchParams.buyerName = '';

                    if (!personId) {
                        filterState.filteredPersons = [...filterAllManData.value];
                        return;
                    }

                    // 2. 查找人员
                    filterState.filteredPersons = [...filterAllManData.value];
                    const personIdStr = String(personId);
                    const selectedPerson = filterState.filteredPersons.find(person => {
                        const personIdTrim = String(person.id).trim();
                        const personIdStrTrim = personIdStr.trim();
                        return personIdTrim === personIdStrTrim;
                    });
                    console.log("选中的Id为:" + personIdStr);
                    if (!selectedPerson) {
                        ElMessage.warning('未找到选中的人员');
                        return;
                    }

                    // 3. 核心修正：判断人员的部门ID是否在部门树中存在
                    const personOrgId = String(selectedPerson.orgId || '').trim();
                    let isDeptValid = false;

                    if (personOrgId) {
                        // 调用递归函数查找部门树中是否存在该部门ID
                        const foundDept = findTreeNode(filterDepartTree.value, personOrgId);
                        isDeptValid = !!foundDept; // 存在则有效
                    }

                    // 若部门ID无效（不存在或为空）
                    if (!isDeptValid) {
                        ElMessage.warning('选中的用户暂未分配有效部门，请选择其他用户');
                        // 重置选中状态，确保不回显
                        filterState.selectedPersonId = '';
                        filterState.selectedPersonName = '';
                        searchParams.buyerName = '';
                        return;
                    }

                    // 4. 部门有效时正常赋值并联动
                    filterState.selectedPersonId = personIdStr;
                    filterState.selectedPersonName = selectedPerson.name;
                    searchParams.buyerName = selectedPerson.name;

                    // 联动部门
                    filterState.selectedDeptId = personOrgId;
                    handleDepartmentChange(personOrgId);
                };

                // --------------------------------------------初始化数据字典--------------------------------------------------
                const initDictData = () => {
                    try {
                        let stockInTypeStr = document.getElementById('app').dataset.stockInTypeList || '[]';
                        stockInTypeStr = decodeURIComponent(stockInTypeStr);
                        const stockInTypeData = JSON.parse(stockInTypeStr);
                        stockInTypeList.value = Array.isArray(stockInTypeData) ? stockInTypeData : [];

                        let orderStatusStr = document.getElementById('app').dataset.stockInOrderStatusList || '[]';
                        orderStatusStr = decodeURIComponent(orderStatusStr);
                        const orderStatusData = JSON.parse(orderStatusStr);
                        const allStatus = Array.isArray(orderStatusData) ? orderStatusData : [];
                        stockinOrderStatusDict.value = allStatus.filter(status => {
                            const statusCode = String(status.Code);
                            return statusCode === '3' || statusCode === '4';
                        });

                        orderStatusOptions.value = stockinOrderStatusDict.value.map(item => ({
                            label: item.Name,
                            value: item.Code
                        }));

                        if (stockInTypeList.value.length === 0) {
                            ElMessage.warning('未加载到入库类型数据，请检查后端字典配置');
                        }
                        if (orderStatusOptions.value.length === 0) {
                            ElMessage.warning('未筛选到符合条件的单据状态（需Code=3/4），请检查状态字典配置');
                        }

                    } catch (e) {
                        console.error('字典解析异常:', e);
                        ElMessage.error('数据字典加载失败');
                        stockInTypeList.value = [];
                        stockinOrderStatusDict.value = [];
                        orderStatusOptions.value = [];
                    }
                };

                // 状态code转name
                const getStatusName = (code) => {
                    if (stockinOrderStatusDict.value.length === 0) {
                        return code;
                    }

                    const targetCode = String(code);
                    const matched = stockinOrderStatusDict.value.find(
                        item => String(item.Code) === targetCode
                    );

                    return matched ? matched.Name : `【状态码 ${targetCode} 无对应名称】`;
                };

                // 加载仓库列表
                const loadWarehouseList = async () => {
                    try {
                        const res = await axios.get('/WhInbound/GetWareHouseInfoForSelect');
                        warehouseList.value = res.data && Array.isArray(res.data) ? res.data : [];
                        console.log("仓库列表",warehouseList.value);
                        if (warehouseList.value.length === 0) ElMessage.info('未查询到仓库数据');
                    } catch (error) {
                        console.error('加载仓库列表失败：', error);
                        ElMessage.error('仓库数据加载失败，请重试');
                        warehouseList.value = [];
                    }
                };

                // 格式化数字
                const formatNumber = (row, column, cellValue) => {
                    const value = cellValue ?? arguments[2];
                    return typeof value === 'number' ? value.toFixed(2) : (value || '0.00');
                };

                // 更新合计
                const updateTotal = () => {
                    totalCategories.value = goodsDetailData.value.length;
                    totalQuantity.value = goodsDetailData.value.reduce((sum, item) => sum + (item.purchaseQuantity || 0), 0);
                    totalAmount.value = goodsDetailData.value.reduce((sum, item) => sum + (item.amount || 0), 0);
                };

                // 保存草稿
                const saveAsDraft = async () => {
                    if (!selectedStockType.value) return ElMessage.warning('请选择入库类型');
                    if (!selectedWarehouseId.value) return ElMessage.warning('请选择仓库');
                    if (!purchaseDate.value) return ElMessage.warning('请选择入库日期');

                    const draftData = {
                        stockOrderNo: purchaseOrderCode.value || '',
                        stockType: selectedStockType.value,
                        warehouseId: selectedWarehouseId.value,
                        stockDate: purchaseDate.value,
                        upOrderNo: relatedOrderCode.value,
                        supplierName: supplierName.value,
                        operatorBy: operatorName.value,
                        remark: remark.value,
                        orderStatus: 0,
                        whInboundDetails: goodsDetailData.value.map(item => ({
                            goodsId: item.goodsId || 0,
                            goodsCode: item.goodsCode,
                            goodsName: item.goodsName,
                            purchaseQuantity: item.purchaseQuantity || 0,
                            purchasePrice: item.purchasePrice || 0,
                            amount: item.amount || 0,
                            remarks: item.remarks
                        })),
                        attachments: tempFileList.value.map(file => ({
                            fileName: file.name,
                            fileSize: file.size
                        }))
                    };

                    try {
                        const res = await axios.post('/WhInbound/SaveAsDraft', draftData, {
                            headers: { 'Content-Type': 'application/json' }
                        });
                        res.data > 0 ? ElMessage.success('草稿保存成功') : ElMessage.error('草稿保存失败');
                    } catch (error) {
                        console.error('保存草稿失败：', error);
                        ElMessage.error('保存请求发送失败，请检查网络');
                    }
                };

                // 关闭页面
                const closeDetail = () => {
                    ElMessageBox.confirm(
                        '当前页面数据未保存，确定要关闭吗？',
                        '确认关闭',
                        { type: 'warning' }
                    ).then(() => window.location.href = '/WhInbound/Index').catch(() => {});
                };

                // 加载供应商列表
                const loadSuppliers = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetSupplierInfoForSelectTable');
                        supplierList.value = res.data && Array.isArray(res.data) ? res.data : [];
                        if (supplierList.value.length === 0) ElMessage.warning('供应商数据格式异常');
                    } catch (err) {
                        console.error('加载供应商失败：', err);
                        ElMessage.error('网络错误，无法加载供应商数据');
                        supplierList.value = [];
                    }
                };

                // 选择供应商后自动填充
                const handleSupplierChange = (supplierId) => {
                    if (isRelatePurchase.value) return;
                    contactPerson.value = '';
                    contactPhone.value = '';
                    if (!supplierId) return;

                    const selectedSupplier = supplierList.value.find(item => item.supplierId === supplierId);
                    if (selectedSupplier) {
                        contactPerson.value = selectedSupplier.contactPerson || '无';
                        contactPhone.value = selectedSupplier.contactPhone || '无';
                    } else {
                        ElMessage.warning('未找到该供应商的关联信息');
                    }
                };

                watch(selectPurchaseOrderDialog, async (isOpen) => {
                    if (isOpen) {
                        // 模态框打开时，初始化人员下拉选项
                        filterState.filteredPersons = [...filterAllManData.value];
                        // 调用初始化方法，加载默认数据（无筛选）
                        await loadPurchaseOrderData();
                    } else {
                        // 模态框关闭时重置所有条件
                        handleReset();
                    }
                });

                // 关联进货单勾选逻辑
                watch(isRelatePurchase, (newVal) => {
                    if (newVal) {
                        relatedOrderCode.value = '';
                        selectedSupplierId.value = '';
                        contactPerson.value = '';
                        contactPhone.value = '';
                        supplierName.value = '';
                    } else {
                        // 关键：取消勾选“关联进货单号”时，清空明细
                        goodsDetailData.value = [];
                        selectedRows.value.detail = [];
                        inboundTotalQuantity.value = 0;
                        inboundTotalAmount.value = 0;
                        totalCategories.value = 0;
                        totalAmount.value = 0;
                        nonPurchaseQuantity.value = 0;
                        receivedQuantity.value = 0;
                    }
                });

                // 单选框选中事件
                const handleRadioSelect = (row) => {
                    selectedPurchaseRow.value = row;
                };

                // 加载进货单数据
                const loadPurchaseOrderData = async () => {
                    try {
                        const res = await axios.get('/WhInbound/OmPurchaseOrderDetailForSelect', {
                            params: {
                                orderNo: searchParams.orderNo,
                                orderStatus: searchParams.orderStatus,
                                supplierName: searchParams.supplierName,
                                buyerName: searchParams.buyerName,
                                orgName: searchParams.orgName,
                                buyerDate: searchParams.buyerDate,
                                page: pagination.currentPage,
                                pageSize: pagination.pageSize
                            }
                        });
                        if (res.data && Array.isArray(res.data)) {
                            const formattedData = res.data.map(item => ({
                                ...item,
                                supplierId: item.SupplierId || item.supplierId
                            }));
                            const start = (pagination.currentPage - 1) * pagination.pageSize;
                            const end = start + pagination.pageSize;
                            tableData.value = formattedData.slice(start, end);
                            pagination.total = formattedData.length;
                        } else {
                            tableData.value = [];
                            pagination.total = 0;
                            ElMessage.info('未查询到进货单数据');
                        }
                    } catch (error) {
                        console.error('加载进货单失败：', error);
                        ElMessage.error('进货单数据加载失败，请重试');
                    }
                };

                //---------------------------------关联单号多条件查询---------------------------------------------
                const fetchPurchaseOrdersByFilters = async () => {
                    try {
                        // 1. 整合六个筛选条件（与前端筛选组件一一对应）
                        const queryFilters = {
                            UpOrderNo: searchParams.orderNo?.trim() || '',
                            OrderStatus: searchParams.orderStatus || '',
                            // 错误：SupplierId: getSupplierIdByName(searchParams.supplierId),
                            SupplierId: searchParams.supplierId ? Number(searchParams.supplierId) : 0, // 直接用ID，转数字
                            BuyerId: filterState.selectedPersonId ? Number(filterState.selectedPersonId) : 0,
                            BuyerOrgId: filterState.selectedDeptId ? Number(filterState.selectedDeptId) : 0,
                            BuyerDate: searchParams.buyerDate || '',
                        };
                        // 打印验证：选择供应商后应显示具体ID（如1、2等），而非0
                        console.log("选中的供应商ID：", queryFilters);
                        // 2. 发送POST请求到后端多条件查询接口
                        const res = await axios.post('/WhInbound/OmPurOrderSelectWithSth', queryFilters, {
                            headers: { 'Content-Type': 'application/json' }
                        });

                        // 3. 处理返回结果（更新表格和分页总数）
                        if (res.data.length > 0) {
                            // 格式化数据并更新表格
                            tableData.value = res.data.map(item => ({
                                ...item,
                                buyerDate: item.buyerDate ? new Date(item.buyerDate) : null, // 注意字段名大小写
                                supplierId: item.supplierId || item.supplierId // 统一字段名
                            }));
                            pagination.total = res.data.length; // 更新分页总条数
                        } else {
                            tableData.value = [];
                            pagination.total = 0;
                            ElMessage.info('未查询到符合条件的进货单');
                        }
                    } catch (error) {
                        console.error('多条件查询进货单失败：', error);
                        ElMessage.error('查询出错，请检查网络或重试');
                    }
                };
                const handleSearch = () => {
                    pagination.currentPage = 1;
                    fetchPurchaseOrdersByFilters();
                };

                //-----------------------------------------------------------------------------------------------------

                const handleReset = () => {
                    // 重置搜索参数
                    searchParams.orderNo = '';
                    searchParams.orderStatus = '';
                    searchParams.supplierName = '';
                    searchParams.buyerName = '';
                    searchParams.orgName = '';
                    searchParams.buyerDate = '';

                    // 重置筛选状态
                    filterState.selectedDeptId = '';
                    filterState.selectedPersonId = '';
                    filterState.filteredPersons = [...filterAllManData.value];

                    // 重置分页和表格
                    pagination.currentPage = 1;
                    pagination.pageSize = 10;
                    loadPurchaseOrderData();
                    selectedPurchaseId.value = '';
                };
                const handlePageSizeChange = (val) => {
                    pagination.pageSize = val;
                    pagination.currentPage = 1;
                    loadPurchaseOrderData();
                    selectedPurchaseId.value = '';
                    selectedPurchaseRow.value = null;
                };
                const handlePageChange = (val) => {
                    pagination.currentPage = val;
                    loadPurchaseOrderData();
                    selectedPurchaseId.value = '';
                    selectedPurchaseRow.value = null;
                };
                const handleSelectionChange = (val) => {
                    selectedPurchaseOrders.value = val;
                };
                // 打开进货单模态框时加载数据
                watch(selectPurchaseOrderDialog, async (newVal) => {
                    if (newVal) {
                        filterState.filteredPersons = [...filterAllManData.value];
                        loadPurchaseOrderData();
                    } else {
                        // 重置搜索参数和状态
                        searchParams.orderNo = '';
                        searchParams.orderStatus = '';
                        searchParams.supplierName = '';
                        searchParams.buyerName = '';
                        searchParams.orgName = '';
                        searchParams.buyerDate = '';
                        selectedPurchaseId.value = '';
                        filterState.selectedDeptId = '';
                        filterState.selectedPersonId = '';
                    }
                });

                // 加载部门数据
                const loadFilterDepartments = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetOrgInfoForSelectTable');
                        console.log('部门接口返回:', res.data);

                        const formatTreeData = (nodes) => {
                            return nodes.map(node => {
                                // 关键：统一字段名，确保有id和name（根据接口返回调整，如接口返回label则用node.label）
                                const formattedNode = {
                                    id: String(node.id || node.orgId || 'default-dept-id'), // 强制字符串，与v-model格式一致
                                    name: node.name || node.label || '未命名部门', // 部门名称字段，适配props的label
                                    children: []
                                };

                                // 递归处理子部门
                                if (node.children && Array.isArray(node.children) && node.children.length > 0) {
                                    formattedNode.children = formatTreeData(node.children);
                                } else if (node.orgChildren && Array.isArray(node.orgChildren) && node.orgChildren.length > 0) {
                                    formattedNode.children = formatTreeData(node.orgChildren);
                                }
                                return formattedNode;
                            });
                        };

                        filterDepartTree.value = formatTreeData(res.data);
                        if (filterDepartTree.value.length === 0) {
                            ElMessage.warning('部门数据格式化后为空，请检查接口字段');
                        }

                    } catch (err) {
                        console.error('部门数据加载失败:', err);
                        ElMessage.error('加载部门数据失败，请检查网络或接口');
                        filterDepartTree.value = [];
                    }
                };

                // 加载人员数据
                const loadFilterPersons = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetUserInfoForSelectTable');
                        console.log('人员接口原始返回:', res.data); // 新增：查看接口是否返回数据
                        if (!Array.isArray(res.data) || res.data.length === 0) {
                            ElMessage.error('人员接口返回空或非数组数据');
                            filterAllManData.value = [];
                            return;
                        }
                        // 关键：确保person.id转为字符串
                        filterAllManData.value = res.data.map(person => ({
                            id: String(person.usersId || 'default-person-id'), // 强制转字符串
                            name: person.usersTrueName || '未知人员',
                            orgId: String(person.orgId || 'default-org-id')
                        }));
                        console.log('格式化后的filterAllManData:', filterAllManData.value); // 新增：查看格式化后的数据
                        filterManData.value = [...filterAllManData.value];
                    } catch (err) {
                        console.error('人员数据加载失败:', err);
                        ElMessage.error('人员数据加载失败');
                        filterAllManData.value = [];
                    }
                };

                // 递归查找树形节点方法
                const findTreeNode = (treeData, targetId) => {
                    let result = null;
                    const traverse = (nodes) => {
                        for (const node of nodes) {
                            if (String(node.id) === String(targetId)) {
                                result = node;
                                return;
                            }
                            if (Array.isArray(node.children) && node.children.length > 0) {
                                traverse(node.children);
                                if (result) return;
                            }
                        }
                    };
                    traverse(treeData);
                    return result;
                };

                //-----------------------------------经办人选择-----------------------------------------
                // 机构树选中的ID
                const selectedOrgId = ref('');
                // 过滤后的人员列表（根据选中机构筛选）
                const filteredUsers = ref([]);
                // 已选择的人员列表
                const selectedUsers = ref([]);

                // 机构树节点点击事件（左侧机构选择）
                const handleOrgSelect = (node) => {
                    selectedOrgId.value = node.id;
                    // 根据机构ID过滤人员：只显示该机构及子机构下的人员
                    filteredUsers.value = filterAllManData.value.filter(person => {
                        const personOrgId = String(person.orgId);
                        // 递归获取当前机构及所有子机构ID
                        const deptIds = getDeptIdsRecursive(node);
                        return deptIds.includes(personOrgId);
                    });
                };

                // 选中人员（中间人员列表点击）
                const handleUserSelect = (user) => {
                    // 核心：清空原有已选人员，只保留当前选中的一个（实现单选替换）
                    selectedUsers.value = [];
                    // 添加当前选中人员
                    selectedUsers.value.push(user);
                };

                // 删除已选人员（右侧已选区域点击X）
                const removeSelectedUser = (index) => {
                    selectedUsers.value.splice(index, 1);
                };

                const confirmOperatorSelect = () => {
                    if (selectedUsers.value.length === 0) {
                        ElMessage.warning('请选择经办人');
                        return;
                    }
                    // 单选逻辑：直接取第一个元素（仅一个）
                    const selectedUser = selectedUsers.value[0];
                    // 赋值经办人ID和名称（适配单选场景）
                    operatorId.value = [selectedUser.id]; // 保持数组格式，兼容后端逻辑
                    operatorName.value = selectedUser.name; // 直接显示单个名称，无需拼接
                    // 关闭弹窗
                    selectOperatorModel.value = false;
                };


                //-----------------------------------经办人选择-----------------------------------------
                // 页面初始化
                onMounted(async () => {
                    initDictData();
                    await loadWarehouseList();
                    await loadSuppliers();
                    await loadFilterDepartments();
                    await loadFilterPersons();

                    // 关键：初始化进货人下拉框数据
                    filterState.filteredPersons = [...filterAllManData.value];
                    getWhInboundNumber()
                });

                //获取入库单号
                const getWhInboundNumber = async () => {
                    try {
                        const res = await axios.post('/NumberingRules/GenerateByRuleId?ruleId=2');

                        // 检查接口返回的成功状态
                        if (res.data && res.data.success) {
                            // 从 res.data.number 提取编号（控制器返回的编号字段）
                            purchaseOrderCode.value = res.data.number;
                            console.log('入库单编号生成成功：', res.data.number);
                        } else {
                            // 接口返回失败信息（如规则ID无效）
                            ElMessage.warning(res.data?.message || '编号生成失败，请检查规则配置');
                            purchaseOrderCode.value = ''; // 清空无效值
                        }
                    } catch (error) {
                        // 捕获网络错误或服务器异常
                        console.error('生成入库单编号请求失败：', error);
                        ElMessage.error('网络错误，无法生成编号，请重试');
                        purchaseOrderCode.value = '';
                    }
                };


                //-----------------------------------添加货品-------------------------------------------
                const selectedGoodsList = ref([]); // 主动存储选中的货品数据

                // 新增：处理货品表格选中事件，实时同步选中数据
                const handleGoodsSelectionChange = (val) => {
                    selectedGoodsList.value = val; // 同步选中数据
                    console.log("当前选中的货品：", selectedGoodsList.value); // 验证是否获取到数据
                };
                const addTableRef = ref(null);
                const openAddGoodsDialog = async () => {
                    // 校验关联单号是否有效
                    if (!relatedOrderCode.value || relatedUpOrderId.value === 0) {
                        ElMessage.warning('请先选择或输入有效的关联单号');
                        return;
                    }

                    try {
                        // 调用后端接口获取货品明细
                        const res = await axios.get('/WhInbound/GetOmPurOrderGoodsDetail', {
                            params: { upOrderId: relatedUpOrderId.value }
                        });

                        if (res.data && Array.isArray(res.data)) {
                            originalGoodsData.value = res.data;
                            goodsTotal.value = res.data.length;
                            handleGoodsPageChange(1);

                            // 关键：等待表格渲染完成后，获取 ref 实例（备用）
                            await nextTick();
                            const tableInstance = addTableRef.value;
                            if (tableInstance) {
                                tableInstance.clearSelection(); // 清空历史选中
                                console.log("表格 ref 绑定成功：", tableInstance);
                            } else {
                                console.warn("表格 ref 未加载，将使用 selection-change 存储的选中数据");
                            }
                        } else {
                            originalGoodsData.value = [];
                            paginatedGoodsData.value = [];
                            goodsTotal.value = 0;
                            ElMessage.info('该关联单号下暂无货品数据');
                        }

                        // 打开弹窗
                        goodsSearchKey.value = '';
                        goodsCurrentPage.value = 1;
                        addGoodsDialog.value = true;
                    } catch (error) {
                        console.error('加载货品明细失败：', error);
                        ElMessage.error('货品数据加载失败，请重试');
                        addGoodsDialog.value = false;
                    }
                };

                const handleGoodsPageChange = (page) => {
                    goodsCurrentPage.value = page;
                    // 计算分页起始/结束索引
                    const startIndex = (page - 1) * goodsPageSize.value;
                    const endIndex = startIndex + goodsPageSize.value;
                    // 截取数据赋值给表格
                    paginatedGoodsData.value = originalGoodsData.value.slice(startIndex, endIndex);
                };

                // 每页条数变化时重置页码并更新数据
                const handleGoodsPageSizeChange = (size) => {
                    goodsPageSize.value = size;
                    handleGoodsPageChange(1); // 重置到第一页
                };

                const getUpOrderIdByNo = async (upOrderNo) => {
                    try {
                        const res = await axios.get('/WhInbound/GetUpOrderIdByNo', {
                            params: { upOrderNo: upOrderNo }
                        });
                        // 假设接口返回 { success: true, data: 123 }（123 为 upOrderId）
                        if (res.data) {
                            relatedUpOrderId.value = res.data.data; // 存储 upOrderId
                            return true;
                        } else {
                            ElMessage.warning('未找到该关联单号对应的进货单');
                            relatedUpOrderId.value = 0;
                            return false;
                        }
                    } catch (error) {
                        console.error('获取 upOrderId 失败：', error);
                        ElMessage.error('网络错误，无法验证关联单号');
                        relatedUpOrderId.value = 0;
                        return false;
                    }
                };

                // 1. 选择关联单号时（修改 confirmSelect 方法，补充获取 upOrderId）
                const confirmSelect = async () => {
                    if (!selectedPurchaseRow.value) return ElMessage.warning('请选择一条进货单');

                    // 关键：清空原有入库明细（选择新关联单号时触发）
                    goodsDetailData.value = [];
                    selectedRows.value.detail = [];
                    inboundTotalQuantity.value = 0;
                    inboundTotalAmount.value = 0;
                    totalCategories.value = 0;
                    totalAmount.value = 0;
                    nonPurchaseQuantity.value = 0;
                    receivedQuantity.value = 0;
                    // 赋值关联单号
                    relatedOrderCode.value = selectedPurchaseRow.value.upOrderNo;
                    // 直接从选中的进货单中获取 upOrderId（无需额外接口，效率更高）
                    relatedUpOrderId.value = selectedPurchaseRow.value.upOrderId;
                    // 其他原有逻辑（供应商、联系人赋值）...
                    const purchaseData = selectedPurchaseRow.value;
                    // 供应商ID（需与表单的 selectedSupplierId 类型一致，通常是数字或字符串）
                    selectedSupplierId.value = purchaseData.supplierId || '';
                    // 供应商名称
                    supplierName.value = purchaseData.supplierName || '';
                    // 联系人
                    contactPerson.value = purchaseData.contactPerson || '无';
                    // 联系方式
                    contactPhone.value = purchaseData.contactPhone || '无';
                    selectPurchaseOrderDialog.value = false;
                };

                // 2. 手动输入关联单号时（监听 relatedOrderCode 变化，可选）
                watch(relatedOrderCode, async (newNo,oldNo) => {
                    // 仅当新旧单号不同，且新单号有效（非空）时，才清空明细
                    if (newNo !== oldNo && newNo) {
                        // 核心：清空入库明细表格数据
                        goodsDetailData.value = [];
                        // 清空明细选中状态，避免残留
                        selectedRows.value.detail = [];
                        // 清空本次入库合计数据
                        inboundTotalQuantity.value = 0;
                        inboundTotalAmount.value = 0;
                        totalCategories.value = 0;
                        totalAmount.value = 0;
                        nonPurchaseQuantity.value = 0;
                        receivedQuantity.value = 0;
                        ElMessage.info(`当前单号发生变化，已清空入库明细`);
                    }
                    if (newNo && !isRelatePurchase.value) { // 手动输入且未勾选“关联进货单号”
                        await getUpOrderIdByNo(newNo); // 验证单号并获取 upOrderId
                    }
                });

                const confirmAddGoods = async () => {
                    // 1. 获取选中的货品数据（从添加货品弹窗的表格）
                    let selectedGoods = [...selectedGoodsList.value];
                    if (selectedGoods.length === 0) {
                        await nextTick();
                        const tableInstance = addTableRef.value;
                        selectedGoods = tableInstance ? tableInstance.getSelectionRows() || [] : [];
                    }
                    if (selectedGoods.length === 0) {
                        ElMessage.warning('请选择要添加的货品');
                        return;
                    }

                    // 2. 遍历选中的货品，逐个判断是否重复
                    for (const goods of selectedGoods) {
                        // 用 goodsCode 作为唯一标识（可根据实际需求调整，如 goodsId + specification）
                        const duplicateItem = goodsDetailData.value.find(
                            item => item.goodsCode === goods.goodsCode
                        );

                        if (duplicateItem) {
                            // 3. 发现重复，弹窗询问用户
                            const confirmResult = await ElMessageBox.confirm(
                                `已存在【${goods.goodsName}】的记录，是否合并数量？`,
                                '重复提示',
                                {
                                    confirmButtonText: '合并',
                                    cancelButtonText: '不合并',
                                    type: 'warning'
                                }
                            );

                            if (confirmResult === 'confirm') {
                                // 4. 选择“合并”：累加本次入库数量
                                duplicateItem.currentInStockQty += goods.currentInStockQty || 0;
                                // 重新计算该货品的入库金额
                                duplicateItem.inboundAmount =
                                    duplicateItem.currentInStockQty * (duplicateItem.purchaseUnitPrice || 0);
                                // 更新合计
                                updateInboundTotal();
                            } else {
                                // 5. 选择“不合并”：跳过当前货品，提示用户
                                ElMessage.info(`已跳过重复货品【${goods.goodsName}】，请手动处理`);
                                continue; // 不添加当前货品，继续判断下一个
                            }
                        } else {
                            // 6. 无重复，正常添加到列表
                            const formattedGoods = {
                                id: goodsDetailData.value.length + 1,
                                goodsCode: goods.goodsCode || '',
                                goodsName: goods.goodsName || '',
                                specification: goods.specification || '',
                                goodsTypeName: goods.goodsTypeName || '未分类',
                                unit: '吨',
                                availableInventoryQty: goods.availableInventoryQty || 0,
                                orderQuantity: goods.orderQuantity || 0,
                                receivedQuantity: goods.receivedQuantity || 0,
                                nonPurchaseQuantity: goods.nonPurchaseQuantity || 0,
                                purchaseUnitPrice: goods.purchaseUnitPrice || 0,
                                currentInStockQty: goods.currentInStockQty || 0, // 取弹窗中输入的数量
                                inboundAmount: (goods.currentInStockQty || 0) * (goods.purchaseUnitPrice || 0),
                                storageLocationId: '',
                                batchNo: '',
                                remarks: ''
                            };
                            goodsDetailData.value.push(formattedGoods);
                        }
                    }

                    // 7. 更新所有合计（合并后需重新计算）
                    updateTotal();
                    updateInboundTotal();

                    // 8. 关闭弹窗并重置
                    addGoodsDialog.value = false;
                    selectedGoodsList.value = [];
                    const tableInstance = addTableRef.value;
                    if (tableInstance) tableInstance.clearSelection();
                };




                //------------------------------入库明细输入--------------------------------------
                // 仓库 ID，用于获取库位数据，可根据实际场景赋值（比如从基础信息的仓库选择中获取）
                const warehouseId = ref();
                // 库位数据列表，用于下拉框
                const locationList = ref([]);

                // 新增1：监听仓库选择变化，同步到 warehouseId 并加载库位
                const handleWarehouseChange = (val) => {
                    // 1. 清空所有货品明细的库位值（核心：切换仓库后库位失效）
                    goodsDetailData.value.forEach(item => {
                        item.storageLocationId = ''; // 清空已选库位
                    });

                    // 2. 重置库位列表（新仓库需重新加载库位）
                    locationList.value = [];

                    // 3. 无仓库选择时直接返回
                    if (!val) {
                        return;
                    }

                    // 4. 有仓库选择时，同步仓库ID（触发库位加载，原逻辑保留）
                    warehouseId.value = val;
                };

                // 新增：点击禁用的库位下拉框时提示
                const handleLocationSelectClick = () => {
                    if (!selectedWarehouseId.value) {
                        ElMessage.warning('请先选择仓库，再选择库位');
                    }
                };

                // 监听仓库 ID 变化获取库位数据
                watch(warehouseId, async (newVal) => {
                    if (!newVal) {
                        locationList.value = [];
                        return;
                    }
                    console.log("当前选择的仓库ID：", newVal);  // 新增：打印日志，验证是否获取到ID
                    try {
                        // 修复：确保接口地址正确（替换/WhInbound为实际控制器名，若接口正确则保留）
                        const res = await axios.get(`/WhInbound/SelectWhLocationForInbound?warehouseId=${newVal}`);
                        if (Array.isArray(res.data)) {
                            locationList.value = res.data;
                        } else {
                            locationList.value = [];
                            ElMessage.info('该仓库下暂无库位数据');
                        }
                    } catch (error) {
                        console.error('获取库位数据失败：', error);
                        ElMessage.error('库位数据加载失败，请重试');
                        locationList.value = [];
                    }
                });

                // 移除单条货品明细
                const removeDetail = (row) => {
                    const index = goodsDetailData.value.findIndex(item => item.id === row.id);
                    if (index > -1) {
                        goodsDetailData.value.splice(index, 1);
                        updateTotal(); // 基础合计
                        updateInboundTotal(); // 本次入库合计（新增）
                    }
                };

                // 批量移除货品明细
                const removeGoodsDetail = () => {
                    if (selectedRows.value.detail.length === 0) {
                        ElMessage.warning('请先选中需要移除的货品');
                        return;
                    }
                    const selectedIds = selectedRows.value.detail.map(item => item.id);
                    goodsDetailData.value = goodsDetailData.value.filter(item => !selectedIds.includes(item.id));
                    selectedRows.value.detail = [];
                    updateTotal(); // 基础合计
                    updateInboundTotal(); // 本次入库合计（新增）
                };

                // 本次入库数量输入处理
                const handleCurrentInStockQtyInput = (row) => {
                    // 1. 先判断输入是否为有效数字，非数字则直接清空（避免字符串、空值干扰）
                    if (isNaN(row.currentInStockQty) || row.currentInStockQty === '' || row.currentInStockQty === null) {
                        row.currentInStockQty = 0;
                        ElMessage.warning('请输入有效的数字');
                        return;
                    }

                    // 2. 定义最大可入库量 = 未入库数量（确保为数字，避免undefined）
                    const maxInStockQty = Number(row.nonPurchaseQuantity) || 0;
                    // 3. 强制转换输入值为数字（避免v-model绑定的字符串类型导致比较失效）
                    const inputQty = Number(row.currentInStockQty);

                    // 4. 校验逻辑：不允许负数，且不允许超过未入库数量
                    if (inputQty < 0) {
                        // 负数时重置为0
                        row.currentInStockQty = 0;
                        ElMessage.warning('本次入库数量不能为负数');
                    } else if (inputQty > maxInStockQty) {
                        // 超限时重置为最大可入库量（输入无效化核心：强制覆盖超量输入）
                        row.currentInStockQty = maxInStockQty;
                        ElMessage.warning(`入库数量不能超过未入库数量（最大可入库${maxInStockQty}吨）`);
                    }

                    // 5. 重新计算当前行的入库金额（确保金额与重置后的数量匹配）
                    row.inboundAmount = (Number(row.purchaseUnitPrice) || 0) * row.currentInStockQty;
                    // 6. 更新合计数据（确保页面合计与当前行数据同步）
                    updateInboundTotal();
                };

                const inboundTotalQuantity = ref(0); // 本次入库总数量
                const inboundTotalAmount = ref(0);   // 本次入库总金额

                // 新增：计算本次入库的数量和金额合计（基于 currentInStockQty）
                const updateInboundTotal = () => {
                    // 1. 本次入库总数量（不变）
                    inboundTotalQuantity.value = goodsDetailData.value.reduce((sum, item) =>
                        sum + (item.currentInStockQty || 0), 0
                    );

                    // 2. 本次入库总金额（不变）
                    inboundTotalAmount.value = goodsDetailData.value.reduce((sum, item) => {
                        const quantity = item.currentInStockQty || 0;
                        const price = item.purchaseUnitPrice || 0;
                        const rowAmount = quantity * price;
                        return sum + rowAmount;
                    }, 0);

                    // 3. 新增：计算所有货品未入库数量总和
                    nonPurchaseQuantity.value = goodsDetailData.value.reduce((sum, item) =>
                        sum + (item.nonPurchaseQuantity || 0), 0
                    );

                    // 4. 新增：计算所有货品已入库数量总和
                    receivedQuantity.value = goodsDetailData.value.reduce((sum, item) =>
                        sum + (item.receivedQuantity || 0), 0
                    );

                    // 同步更新总金额（不变）
                    totalAmount.value = inboundTotalAmount.value;
                };
                const calculateInboundAmount = (row) => {
                    // 避免空值导致计算错误，默认值设为 0
                    const quantity = row.currentInStockQty || 0; // 本次入库数量
                    const price = row.purchaseUnitPrice || 0;    // 进货单价
                    const amount = quantity * price;             // 实时计算金额
                    return amount.toFixed(2); // 保留2位小数，与其他数值列格式统一
                };

                const nonPurchaseQuantity = ref(0); // 所有货品未入库数量总和
                const receivedQuantity = ref(0);    // 所有货品已入库数量总和

                //-----------------------------------添加货品结束-------------------------------------------



                //-----------------------------------上传附件-------------------------------------------

                const tempFileList = ref([]);

                // 处理文件超出限制
                const handleFileExceed = (files, uploadFiles) => {
                    ElMessage.warning(`最多只能选择10个文件，当前已选择${uploadFiles.length + files.length}个`);
                };

                // 处理文件选择
                const handleFileSelect = (uploadFile) => {
                    const isDuplicate = tempFileList.value.some(file => file.name === uploadFile.name);
                    if (!isDuplicate) tempFileList.value.push(uploadFile);
                    else ElMessage.info(`文件「${uploadFile.name}」已存在`);
                };

                //上传附件
                const handleUploadSuccess = (response, uploadFile) => {
                    if (response.success) {
                        // 找到当前上传的文件，添加 fileId 字段
                        const fileIndex = tempFileList.value.findIndex(item => item.uid === uploadFile.uid);
                        if (fileIndex > -1) {
                            tempFileList.value[fileIndex].fileId = response.data.fileId; // 存储 fileId
                        } else {
                            // 若未找到，直接添加到列表（包含 fileId）
                            tempFileList.value.push({
                                ...uploadFile,
                                fileId: response.data.fileId
                            });
                        }
                        ElMessage.success(response.message);
                    } else {
                        ElMessage.error(response.message);
                        // 上传失败，从列表中移除该文件
                        const fileIndex = tempFileList.value.findIndex(item => item.uid === uploadFile.uid);
                        if (fileIndex > -1) {
                            tempFileList.value.splice(fileIndex, 1);
                        }
                    }
                };

                // 2. 移除临时文件（点击删除按钮时）：调用删除接口
                const removeTempFile = async (index) => {
                    const file = tempFileList.value[index];
                    if (!file.fileId) {
                        // 若未上传成功（无 fileId），直接从列表移除
                        tempFileList.value.splice(index, 1);
                        return;
                    }

                    try {
                        // 调用控制器的删除接口
                        const res = await axios.post('/WhInbound/DeleteAttachment', {
                              FileId: file.fileId // 传递 fileId 给后端
                        });

                        if (res.data.success) {
                              ElMessage.success(res.data.message);
                              // 从前端列表中移除
                              tempFileList.value.splice(index, 1);
                        } else {
                              ElMessage.error(res.data.message);
                        }
                    } catch (error) {
                        console.error('删除附件失败：', error);
                        ElMessage.error('网络错误，文件删除失败');
                    }
                };

                // 3. （可选）修改 handleFileRemove：选择文件前删除已选文件时触发
                const handleFileRemove = async (uploadFile, uploadFiles) => {
                    if (!uploadFile.fileId) return; // 未上传成功，无需调用接口
                    try {
                        await axios.post('/WhInbound/DeleteAttachment', { FileId: uploadFile.fileId });
                    } catch (error) {
                        console.error('移除已上传文件失败：', error);
                        ElMessage.error('已上传文件移除失败，请手动删除');
                    }
                };

                //-----------------------------------上传附件结束---------------------------------------



                //-----------------------------------新增部分-------------------------------------------
                
                //保存
                const saveThis = async () => {
                    // 1. 基础校验（必选字段）
                    if (!selectedStockType.value) return ElMessage.warning('请选择入库类型');
                    if (!selectedWarehouseId.value) return ElMessage.warning('请选择仓库');
                    if (!purchaseDate.value) return ElMessage.warning('请选择入库日期');
                    if (!operatorId.value || operatorId.value.length === 0) return ElMessage.warning('请选择经办人');
                    if (goodsDetailData.value.length === 0) return ElMessage.warning('请添加至少一条进货明细');

                    //禁用保存按钮
                    saveBtnDisabled.value = true;

                    // 2. 生成同批附件的共用 Code（用 GUID 确保唯一）
                    const commonAttachmentCode = 'ATT-' + window.crypto.randomUUID(); // 格式示例：ATT-550e8400-e29b-41d4-a716-446655440000

                    // 3. 组装入库单主表数据（WhInboundForAdd 格式）
                    const inboundMain = {
                        WareHouseId: selectedWarehouseId.value, // 仓库ID（对应实体字段）
                        StockOrderNo: purchaseOrderCode.value,  // 入库单号（自动生成）
                        SourceOrderNo: relatedOrderCode.value || '', // 关联单号（可选）
                        StockDate: purchaseDate.value,          // 入库日期
                        StockType: selectedStockType.value,     // 入库类型
                        OperatorBy: operatorId.value[0],        // 经办人ID（取已选第一个，若支持多经办人需调整）
                        OperatorDate: new Date()                // 经办时间（当前时间）
                    };

                    // 4. 组装入库明细数据（WhInboundDetailForAdd 格式，给 attachmentCode 赋值共用Code）
                    const inboundDetails = goodsDetailData.value.map(detail => ({
                        StockOrderId: 0, // 主表ID，后端插入后赋值，前端暂填0
                        GoodsCode: detail.goodsCode || '', // 商品编号
                        StorageLocationId: detail.storageLocationId || 0, // 库位ID
                        CurrentStockInQuantity: detail.currentInStockQty || 0, // 本次入库数量
                        OrderQuantity: detail.orderQuantity || 0, // 进货数量
                        ProductUnit: detail.unit || '吨', // 货品单位
                        PurchaseUnitPrice:detail.purchaseUnitPrice,
                        BatchNo: detail.batchNo || '', // 批次号
                        PurchaseAmount: detail.inboundAmount || 0, // 进货金额（本次入库数量×单价）
                        AttachmentCode: commonAttachmentCode, // 关键：填入共用附件Code
                        Remarks: detail.remarks || '' // 备注
                    }));

                    // 5. 组装附件列表数据（SysAttachmentDTO 格式，同样赋值共用Code）
                    const attachments = tempFileList.value.map(file => ({
                        AttachmentCode: commonAttachmentCode, // 关键：同批附件共用一个Code
                        AttachmentAddress: file.savePath || '', // 服务器文件路径（上传时后端返回的savePath）
                        CreateBy: operatorId.value[0].toString(), // 创建人（经办人ID）
                        CreateTime: new Date(), // 创建时间
                        UpdateBy: operatorId.value[0].toString(), // 修改人（同创建人）
                        UpdateTime: new Date() // 修改时间
                    }));

                    const attachmentFileIds = tempFileList.value
                    .filter(file => file.fileId) // 只保留有 fileId 的（上传成功的）
                    .map(file => file.fileId);   // 提取 fileId 组成数组

                    // 6. 发送保存请求（调用后端 AddWhInbound 接口）
                    try {
                        const res = await axios.post('/WhInbound/AddWhInbound',
                            {
                                inboundMain: inboundMain,
                                inboundDetails: inboundDetails,
                                attachments: attachments,
                                attachmentFileIds: attachmentFileIds // 关键：传递 fileId 列表给后端
                            },
                            { headers: { 'Content-Type': 'application/json' } }
                        );

                        if (res.data.success) {
                            ElMessage.success('入库单保存成功');
                            //按钮禁用3秒
                            setTimeout(() => {
                                saveBtnDisabled.value = false;
                            }, 3000);
                            setTimeout(() => window.location.href = '/WhInbound/Index', 500);
                            axios.post('/NumberingRules/GenerateAndUpdateNumber?ruleId=2')
                            .then(res=>{
                                console.log('入库单号已刷新')
                            })
                        } else {
                            ElMessage.error(`保存失败：${res.data.message}`);
                        }
                    } catch (error) {
                        console.error('保存入库单请求异常：', error);
                        ElMessage.error('网络错误，保存失败，请重试');
                        // 网络异常时，后端可能未处理，可考虑前端主动调用删除接口（可选）
                        // 如需前端兜底：await Promise.all(attachmentFileIds.map(id => deleteAttachment(id)));
                    }
                };
                const saveAndAdd = () => ElMessage.info('保存并新增功能待实现');
                const searchGoods = () => ElMessage.info('货品搜索功能待实现');

                //-----------------------------------新增部分结束

                return {
                    handleDateChange,
                    purchaseOrderCode,
                    selectOperatorModel,
                    selectedStockType,
                    stockInTypeList,
                    selectedWarehouseId,
                    warehouseList,
                    purchaseDate,
                    relatedOrderCode,
                    isRelatePurchase,
                    supplierName,
                    contactPerson,
                    contactPhone,
                    operatorName,
                    remark,
                    getStatusName,
                    goodsDetailData,
                    tempFileList,
                    totalCategories,
                    totalQuantity,
                    totalAmount,
                    addGoodsDialog,
                    goodsSearchKey,
                    goodsCurrentPage,
                    goodsPageSize,
                    goodsTotal,
                    paginatedGoodsData,
                    supplierList,
                    selectedSupplierId,
                    handleSupplierChange,
                    selectPurchaseOrderDialog,
                    searchParams,
                    orderStatusOptions,
                    tableData,
                    pagination,
                    handleSearch,
                    handleReset,
                    handlePageSizeChange,
                    handlePageChange,
                    handleSelectionChange,
                    
                    formatNumber,
                    removeDetail,
                    removeGoodsDetail,
                    handleFileExceed,
                    handleFileSelect,
                    removeTempFile,
                    saveAsDraft,
                    closeDetail,

                    searchGoods,
                    selectedPurchaseId,
                    handleRadioSelect,
                    filterDepartList,
                    treeProps,
                    filterManData,
                    handleDepartmentChange,
                    handlePersonChange,
                    findTreeNode,
                    filterState,
                    filterDepartTree,
                    filterAllManData,
                    // 新增1. 选择人员弹窗相关变量
                    selectOperatorModel,  // 弹窗显示控制
                    selectedOrgId,        // 选中的机构ID
                    filteredUsers,        // 筛选后的人员列表
                    selectedUsers,        // 已选择的人员列表

                    // 2. 机构/人员交互方法
                    handleOrgSelect,      // 机构树节点点击事件（筛选人员）
                    handleUserSelect,     // 人员选择事件（添加到已选）
                    removeSelectedUser,   // 删除已选人员
                    confirmOperatorSelect, // 确认选择人员（赋值给主表单）
                    operatorId,

                    //入库明细
                    selectedPurchaseRow,
                    addTableRef,
                    handleGoodsPageSizeChange,
                    confirmAddGoods,
                    openAddGoodsDialog,
                    handleGoodsPageChange,
                    confirmSelect,
                    handleGoodsSelectionChange,

                    //入库输入详情
                    warehouseId,
                    locationList,
                    goodsDetailData,
                    handleCurrentInStockQtyInput,
                    updateTotal,
                    inboundTotalQuantity,
                    inboundTotalAmount,
                    calculateInboundAmount,
                    updateInboundTotal,
                    handleWarehouseChange,
                    handleLocationSelectClick,
                    nonPurchaseQuantity, 
                    receivedQuantity,    
                    inboundTotalQuantity,


                    //上传附件
                    handleUploadSuccess,
                    handleFileRemove,

                    //保存
                    saveThis,
                    saveAndAdd
                };
            }
        });
        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>

